<template>
  <div class="exam-page flex-col">
    <div class="exam-selected-section flex-col">
      <div class="exam-option-group flex-row justify-between">
        <div class="exam-option" v-for="option in options" :key="option.value" @click="selectOption(option.value)"
          :class="{ selected: selectedOption === option.value }">
          {{ option.label }}
        </div>
        <div class="user-section">
          <template v-if="isLogin">
            <div class="el-dropdown">
              <div class="oj-navbar-name el-tooltip__trigger" role="button" tabindex="0">
              </div>
            </div>
          </template>
        </div>
      </div>
      <div class="center-box">
        <span class="exam-list-title">推荐竞赛</span>
        <el-form inline="true" class="exam-navigation flex-row justify-between">
          <el-form-item label="竞赛时间" prop="datetimerange" class="exam-navigation-box">
            <el-date-picker 
              style="width:360px;" 
              v-model="dateRange" 
              type="datetimerange" 
              range-separator="至"
              start-placeholder="开始时间" 
              end-placeholder="结束时间"
              value-format="YYYY-MM-DD HH:mm:ss"
              @change="handleDateChange">
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button @click="onSearch" plain type="primary">搜索</el-button>
            <el-button @click="onReset" plain type="info">重置</el-button>
          </el-form-item>
        </el-form>
        <!-- </div> -->
        <div class="exam-list-group flex-row">
          <div class="exam-list-item flex-col" v-for="(exam, index) in examList" :key="index">
            <div>
              <img src="@/assets/images/exam.png">
            </div>
            <div class="right-info">
              <span class="exam-title">{{ exam.title }}</span>
              <div class="exam-content flex-col justify-between">
                <span>开赛时间：{{ exam.startTime }}</span>
                <span>结束时间：{{ exam.endTime }}</span>
              </div>
              <div class="exam-button-container">
                <span class="exam-hash-entry" v-if="isOngoingAndUnregisteredCompetition(exam)">已开赛</span>
                <span class="exam-hash-entry" v-if="isEntryAndNotStart(exam)">已报名</span>
                <div v-if="isHistoryExam(exam)">
                  <el-button class="exam-practice-button" type="primary" plain
                    @click="goExam(exam)">竞赛练习</el-button>
                  <el-button class="exam-rank-button" type="primary" plain
                    @click="togglePopover(exam.examId)">查看排名</el-button>
                </div>
                <el-button class="exam-start-button" type="primary" plain v-if="isStartExam(exam)"
                  @click="goExam(exam)">开始答题</el-button>
                <el-button class="exam-enter-button" type="primary" plain v-if="isCanEntry(exam)"
                  @click="enterExam(exam.examId)">报名参赛</el-button>
              </div>
            </div>
          </div>
        </div>
        <div class="exam-page-pagination flex-row">
          <el-pagination background layout="total, sizes, prev, pager, next, jumper" :total="total"
            v-model:current-page="params.pageNum" v-model:page-size="params.pageSize" :page-sizes="[3, 6, 9, 12]"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
      </div>
    </div>
  </div>

  <el-dialog v-model="dialogVisible" width="600px" top="30vh" :show-close="true" :close-on-click-modal="false"
    :close-on-press-escape="false" class="oj-login-dialog-centor" center>
    <el-table :data="examRankList">
      <el-table-column label="排名" prop="examRank" />
      <el-table-column label="用户昵称" prop="nickName" />
      <el-table-column label="用户得分" prop="score" />
    </el-table>
    <el-pagination class="range_page" background layout="total, sizes, prev, pager, next, jumper" :total="rankTotal"
      v-model:current-page="rankParams.pageNum" v-model:page-size="rankParams.pageSize" :page-sizes="[5, 10, 15, 20]"
      @size-change="handleRankSizeChange" @current-change="handleRankCurrentChange" />
  </el-dialog>

</template>

<script setup>
import { reactive, ref, onMounted } from 'vue'
import { getExamListService,enterExamService, getExamRankListService, getExamFirstQuestionService } from '@/apis/exam'
import { getToken } from '@/utils/cookie'
import { getUserInfoService } from '@/apis/user'
import { useRouter } from 'vue-router'
import Navbar from '@/components/Navbar.vue'

//参数定义
const examList = ref([]) //题目列表
const total = ref(0)
const selectedOption = ref(0); // 初始化选中的文本
const dateRange = ref(null) // 用于日期选择器的值
const options = ref([
  { label: '未完赛', value: 0 },
  { label: '历史竞赛', value: 1 },
])
const params = reactive({
  pageNum: 1,
  pageSize: 9,
  type: 0
})
const isLogin = ref(false)
const userInfo = ref({})
const router = useRouter()

// 获取用户信息
async function getUserInfo() {
  try {
    const res = await getUserInfoService()
    userInfo.value = res
    isLogin.value = true
  } catch (error) {
    isLogin.value = false
  }
}

// 跳转到用户中心
function goToUserCenter() {
  router.push('/c-oj/home/user/detail')
}

// 页面加载时检查登录状态
onMounted(() => {
  isLogin.value = !!getToken()
  selectedOption.value = 0
  params.type = 0
  getExamList()
})

// 处理日期变化
function handleDateChange(val) {
  if (val) {
    params.startTime = val[0]
    params.endTime = val[1]
  } else {
    delete params.startTime
    delete params.endTime
  }
}

//竞赛列表
async function getExamList() {
  // 确保type参数与当前选中的选项一致
  params.type = selectedOption.value
  const result = await getExamListService(params)
  examList.value = result.rows
  total.value = result.total
}

async function selectOption(type) {
  selectedOption.value = type
  params.pageNum = 1
  params.type = type
  getExamList()
}

// 搜索/重置
function onSearch() {
  params.pageNum = 1
  // 确保type参数与当前选中的选项一致
  params.type = selectedOption.value
  getExamList()
}

function onReset() {
  params.pageNum = 1
  params.pageSize = 9
  // 保持当前选中的类型（未完赛或历史竞赛）
  params.type = selectedOption.value
  dateRange.value = null // 清除日期选择器的值
  delete params.startTime
  delete params.endTime
  getExamList()
}

// 分页
function handleSizeChange(newSize) {
  params.pageNum = 1
  getExamList()
}

function handleCurrentChange(newPage) {
  getExamList()
}

function isOngoingAndUnregisteredCompetition(exam){
  const now = new Date(); //当前时间
  return new Date(exam.startTime) < now && new Date(exam.endTime) > now && !exam.enter
}

function isEntryAndNotStart(exam) {
  const now = new Date();
  return new Date(exam.startTime) > now && exam.enter
}

function isHistoryExam(exam) {
  const now = new Date();
  return new Date(exam.endTime) < now;
}

function isStartExam(exam) {
  const now = new Date();
  return new Date(exam.startTime) < now && new Date(exam.endTime) > now && exam.enter;
}

function isCanEntry (exam) {
  const now = new Date();
  return new Date(exam.startTime) > now && !exam.enter;
}

async function enterExam(examId) {
  await getUserInfo()
  if (!isLogin.value) {
    ElMessage.error('请先登录后报名参赛,谢谢')
    return
  }
  const enterExamDTO = ref({
    examId: examId
  })
  await enterExamService(enterExamDTO.value)
  ElMessage.success('您已报名成功，请按时参赛',)
  getExamList() //报名成功后刷新竞赛列表
}

async function goExam(exam) {
  try {
    // 获取竞赛中第一道题目的ID
    const response = await getExamFirstQuestionService(exam.examId);
    const questionId = response.data;
    
    // 跳转到答题页面，传递必要参数
    router.push({
      path: '/c-oj/answer',
      query: {
        examId: exam.examId,
        questionId: questionId,
        examTitle: exam.title,
        examEndTime: exam.endTime
      }
    });
  } catch (error) {
    ElMessage.error('获取题目失败，请稍后再试');
    console.error('获取第一题失败：', error);
  }
}

const rankParams = reactive({
  examId:'',
  pageNum: 1,
  pageSize: 9,
})
const examRankList = ref([])
const rankTotal = ref(0)

// 分页
function handleRankSizeChange(newSize) {
  rankParams.pageNum = 1
  getExamRankList()
}

function handleRankCurrentChange(newPage) {
  getExamRankList()
}

const dialogVisible = ref(false)

async function getExamRankList() {
  const result = await getExamRankListService(rankParams)
  examRankList.value = result.rows
  rankTotal.value = result.total
}

function togglePopover(examId) {
  dialogVisible.value = true
  rankParams.examId = examId
  getExamRankList()
}

// 跳转到登录页
function goToLogin() {
  router.push('/c-oj/login')
}

function goLogin() {
  router.push('/c-oj/login')
}

const messageList = JSON.parse(sessionStorage.getItem('messageList') || '[]')

</script>

<style lang="scss" scoped>
@use "sass:color";

// 主题变量
$primary-color: #32C5FF;
$primary-hover: #28b8e6;
$bg-color: #F7F7F7;
$card-bg: #F9F9F9;
$text-primary: #222222;
$text-secondary: #666666;
$text-light: #999999;
$border-radius-base: 8px;
$border-radius-card: 12px;
$box-shadow-base: 0px 2px 10px rgba(0, 0, 0, 0.05);
$box-shadow-hover: 0px 6px 16px rgba(0, 0, 0, 0.1);
$transition-ease: all 0.3s ease;

.exam-page {
  background-color: $bg-color;
  position: relative;
  overflow: hidden;
  display: flex;
  animation: fadeIn 0.6s ease;

  .center-box {
    max-width: 1520px;
    margin: 0 auto;
    width: 100%;
    min-height: 368px;
    background: #fff;
    border-radius: 16px;
    padding: 0 20px;
    padding-top: 30px;
    margin-top: 10px;
    box-shadow: $box-shadow-base;
    transition: $transition-ease;

    &:hover {
      box-shadow: $box-shadow-hover;
    }
  }

  .exam-selected-section {
    margin: 0 auto;
    margin-bottom: 20px;
    position: relative;
    padding-top: 50px;
    max-width: 1520px;
    width: 100%;

    .exam-option-group {
      width: 100%;
      justify-content: flex-start;
      padding-right: 20px;

      .user-section {
        display: flex;
        align-items: center;
      }

      .oj-navbar-name {
        cursor: pointer;
        font-size: 16px;
        color: $primary-color;
        transition: $transition-ease;
        font-weight: 500;
        padding: 5px 10px;
        border-radius: $border-radius-base;
        display: flex;
        align-items: center;
        justify-content: center;

        .oj-head-image {
          width: 40px;
          height: 40px;
          border-radius: 50%;
          object-fit: cover;
          border: 2px solid $primary-color;
          transition: $transition-ease;

          &:hover {
            border-color: color.adjust($primary-color, $lightness: -10%);
            box-shadow: 0 4px 12px rgba(50, 197, 255, 0.2);
          }
        }
      }

      .exam-option {
        cursor: pointer;
        padding: 10px 20px;
        border-bottom: 2px solid transparent;
        transition: $transition-ease;
        font-family: PingFangSC, PingFang SC;
        font-weight: 600;
        font-size: 18px;
        color: $text-primary;
        height: 50px;
        width: fit-content;
        display: flex;
        justify-content: center;
        align-items: center;
        margin-right: 8px;
        &:last-child {
          margin-right: 0;
        }
        position: relative;
        overflow: hidden;

        &::after {
          content: '';
          position: absolute;
          bottom: 0;
          left: 0;
          width: 0;
          height: 2px;
          background-color: $primary-color;
          transition: width 0.3s ease;
        }

        &:hover {
          color: $primary-color;
          transform: translateY(-2px);

          &::after {
            width: 100%;
          }
        }

        &.selected {
          color: $primary-color;
          border-bottom: 2px solid $primary-color;

          &::after {
            width: 100%;
          }
        }

        &:active {
          transform: scale(0.95);
        }
      }
    }

    .exam-list-title {
      height: 24px;
      font-family: PingFangSC, PingFang SC;
      font-weight: 600;
      font-size: 18px;
      color: $text-primary;
      line-height: 25px;
      text-align: left;
      margin-bottom: 30px;
      display: block;
      animation: slideInDown 0.6s ease;
    }

    :deep(.exam-navigation) {
      width: 100%;
      height: auto;
      font-size: 16px;
      margin-bottom: 30px;
      display: flex;
      flex-wrap: wrap;
      align-items: center;
      justify-content: space-between;
      animation: slideInUp 0.6s ease;

      .el-form-item {
        margin-right: 20px;
        margin-bottom: 10px;
      }

      .el-form-item__label {
        background: #fff;
        font-weight: 500;
      }

      .exam-navigation-box {
        background-color: transparent;
        border-radius: $border-radius-base;
        padding: 5px 10px;
        height: auto;
        font-weight: 500;
        transition: $transition-ease;

        &:hover {
          background-color: rgba(232, 233, 234, 1);
          transform: translateY(-2px);
        }
      }

      .el-button {
        position: relative;
        overflow: hidden;
        transition: $transition-ease;
        border-radius: $border-radius-base;
        padding: 10px 20px;
        z-index: 1;

        &::before {
          content: '';
          position: absolute;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
          background: linear-gradient(45deg, transparent, rgba(255, 255, 255, 0.2), transparent);
          transform: translateX(-100%);
          transition: transform 0.6s ease;
          z-index: -1;
        }

        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);

          &::before {
            transform: translateX(100%);
          }
        }

        &:active {
          transform: scale(0.95);
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
        }
      }
    }

    .exam-list-group {
      flex-wrap: wrap;
      animation: fadeIn 0.8s ease;

      @media screen and (min-width: 1420px) {
        .exam-list-item {
          width: 32%;
          &:nth-of-type(3n) {
            margin-right: 0;
          }
        }
      }

      @media screen and (max-width: 1419px) {
        .exam-list-item {
          width: 48%;
          margin-right: 2%;
          &:nth-of-type(2n) {
            margin-right: 0;
          }
        }
      }

      @media screen and (max-width: 970px) {
        .exam-list-item {
          width: 100%;
          margin-right: 0;
        }
      }

      .exam-list-item {
        height: auto;
        min-height: 220px;
        background: $card-bg;
        border-radius: $border-radius-card;
        margin-right: 2%;
        margin-bottom: 25px;
        padding: 24px;
        box-sizing: border-box;
        display: flex;
        align-items: center;
        flex-direction: row;
        justify-content: space-between;
        cursor: pointer;
        transition: $transition-ease;
        box-shadow: $box-shadow-base;
        position: relative;
        overflow: hidden;

        &::before {
          content: '';
          position: absolute;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
          background: linear-gradient(45deg, transparent, rgba(255, 255, 255, 0.1), transparent);
          transform: translateX(-100%);
          transition: transform 0.6s ease;
        }

        .right-info {
          width: calc(100% - 146px);
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          height: 100%;
        }

        .exam-title {
          height: auto;
          min-height: 26px;
          font-family: PingFangSC, PingFang SC;
          font-weight: 600;
          font-size: 20px;
          color: $text-primary;
          line-height: 1.4;
          text-align: left;
          max-width: 100%;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          margin-bottom: 18px;
          display: block;
          transition: color 0.3s ease;
        }

        .exam-content {
          margin-bottom: 26px;
          span {
            height: auto;
            font-family: PingFangSC, PingFang SC;
            font-weight: 400;
            font-size: 16px;
            color: $text-secondary;
            line-height: 1.5;
            display: block;
            margin-bottom: 12px;
            transition: color 0.3s ease;
          }
        }

        img {
          width: 126px;
          height: 180px;
          border-radius: $border-radius-base;
          object-fit: cover;
          transition: transform 0.3s ease;
        }

        &:hover {
          background: #fff;
          box-shadow: $box-shadow-hover;
          transform: translateY(-3px);

          &::before {
            transform: translateX(100%);
          }

          .exam-title {
            color: $primary-color;
          }

          img {
            transform: scale(1.03);
          }

          .exam-content span {
            color: $text-primary;
          }
        }

        &:active {
          transform: scale(0.98) translateY(2px);
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
        }

        .exam-hash-entry {
          float: right;
          font-size: 18px;
          font-family: PingFangSC-Regular, PingFang SC;
          font-weight: 400;
          color: $text-light;
          padding: 5px 10px;
          border-radius: 4px;
          background-color: #f0f0f0;
          transition: all 0.3s ease;
        }

        .exam-button-container {
          display: flex;
          justify-content: space-between;
          align-items: center;
          flex-wrap: wrap;
          gap: 10px;

          .el-button {
            width: 120px;
            height: 44px;
            background: $bg-color;
            border-radius: 6px;
            border: 1px solid $primary-color;
            font-family: PingFangSC, PingFang SC;
            font-weight: 400;
            font-size: 18px;
            color: $primary-color;
            line-height: 44px;
            text-align: center;
            transition: $transition-ease;

            &:hover {
              background: color.adjust($primary-color, $lightness: 40%);
              color: color.adjust($primary-color, $lightness: -10%);
              transform: translateY(-2px);
              box-shadow: 0 4px 12px rgba(50, 197, 255, 0.2);
            }

            &:active {
              transform: scale(0.96);
              background: color.adjust($primary-color, $lightness: 35%) !important;
            }
          }
        }
      }
    }

    .exam-page-pagination {
      width: 100%;
      height: auto;
      margin: 30px 0 73px 0;
      display: flex;
      justify-content: center;
      animation: slideInUp 0.6s ease;

      :deep(.el-pagination) {
        padding: 10px;
        background-color: $card-bg;
        border-radius: $border-radius-base;
        box-shadow: $box-shadow-base;
        transition: $transition-ease;

        &:hover {
          box-shadow: $box-shadow-hover;
        }

        .el-pagination__sizes,
        .el-pagination__jump {
          margin-left: 16px;
        }

        button:not(:disabled) {
          transition: $transition-ease;
          &:hover {
            color: $primary-color;
            transform: translateY(-2px);
          }
          &:active {
            transform: scale(0.9);
          }
        }

        .el-pager li:not(.disabled) {
          transition: $transition-ease;
          &:hover {
            color: $primary-color;
            transform: translateY(-2px);
          }
          &:active {
            transform: scale(0.9);
          }
          &.active {
            background-color: $primary-color;
            color: #fff;
            transform: translateY(-2px);
          }
        }
      }
    }
  }
}

// 动画关键帧
@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@keyframes slideInDown {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes slideInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

// 响应式调整
@media screen and (max-width: 768px) {
  .exam-selected-section {
    .exam-option-group {
      width: 100%;
      justify-content: center;
      .exam-option {
        font-size: 16px;
        padding: 8px;
      }
    }
    :deep(.exam-navigation) {
      flex-direction: column;
      align-items: stretch;
      .el-form-item {
        margin-right: 0;
        width: 100%;
        .el-date-picker {
          width: 100% !important;
        }
      }
    }
    .center-box {
      padding: 0 10px;
      padding-top: 20px;
    }
  }
  .exam-page-pagination {
    margin: 20px 0 40px 0;
  }
}

// 对话框样式优化
:deep(.oj-login-dialog-centor) {
  .el-dialog__header {
    padding: 20px;
    border-bottom: 1px solid #f0f0f0;
    .el-dialog__title {
      font-weight: 600;
      color: $text-primary;
    }
  }
  .el-dialog__body {
    padding: 24px;
  }
  .el-table {
    border-radius: $border-radius-base;
    overflow: hidden;
    margin-bottom: 20px;
    box-shadow: $box-shadow-base;
    transition: $transition-ease;

    &:hover {
      box-shadow: $box-shadow-hover;
    }

    th.el-table__cell {
      background-color: #f5f7fa;
      font-weight: 600;
      color: $text-secondary;
    }
    .el-table__row:hover > td.el-table__cell {
      background-color: color.adjust($primary-color, $lightness: 45%);
    }
  }
}
</style>





